'use strict';

import React from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions/mjs1';
import { Button,Tab,Icon,Dialog,Field,Form,Search,Badge,Radio} from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import Tools from 'utils/index';
import linkConfig from 'utils/urls';
import MainNotice from 'components/main-notice/index';
import SystemDialog from 'components/system-dialog/index';
import ZhekouTags from 'components/zhekou-tags/index';
import FormMjs1Step1 from 'components/form-mjs1-step1/index';
import FormMjs1Step2 from 'components/form-mjs1-step2/index';
import FormMjs1Step3 from 'components/form-mjs1-step3/index';
import './index.scss';

const links = Tools.isLocal() ? linkConfig.local : linkConfig.onLine;
class Mjs1 extends React.Component {
  constructor(props) {
    super(props);
	 this.field = new Field(this, {
		scrollToFirstError:true,
		onChange: (name, value) => {
			if(name!="tagName"){
				this.setState({overlayVisible:false});
			}
		}
	 });
    this.dispatch = this.props.dispatch;
    this.state={
    			overlayVisible:false,
    			curStep:1,
    			count1:0
    		}
  }
  componentDidMount(){
		if(this.props.location.state && this.props.location.state.createNew=="true")
	  	{
			this.props.dispatch(actions.createNew());
		}
  }
  componentWillReceiveProps(nextProps){
		if(nextProps.mjs1.dbId){
			if(this.field.getValue("participate_range")=="1"){
				this.props.history.push({pathname:"mjs1_set_items",state:{dbId:nextProps.mjs1.dbId}});
			}else{
				Dialog.alert({content:"创建活动完成！",onOk:()=>{
					this.props.history.push("mjs1_list");
				}});
			}
		}
  }

	setTag(tagName){
		this.setState({isSelectTag:true});
		this.props.dispatch(actions.setField("name",tagName));
		this.field.setValues({"name":tagName});
	}
	searchResult(hasTag,isPrefect){
		this.setState({"hasTag":hasTag,"isPrefect":isPrefect});
	}
	checkTag(rule,tagName,callback){
		this.setState({"search":tagName});
		if(this.state.isSelectTag){
			callback()
		}else{
			callback("请您从列表中选择标签！不可输入后直接提交")
		}
	}
  onVisibleChange = (visible) => {
      this.setState({
          overlayVisible:visible,
			isSelectTag:false
      });
  }
 handleToStep(step){
	 if(step<4){
		 this.setState({curStep:step});
	 }else{
		 //第四步
		 this.field.validate((errors, values) => {
	         if (errors) {
	        	 		let count1=0;
	        	 		let count2=0;
	        	 		let count3=0;
	        	 		for(var err in errors){ 
	        	 			  switch(err){
	        	 			  		case "name": count1++;break;
			        	 			case "start_time": count1++;break;
			        	 			case "end_time": count1++;break;
			        	 			case "item_count": count1++;break;
			        	 			case "total_price": count1++;break;
	        	 			  }
	        	 		}
	        	 		this.setState({count1});
	        	 		Dialog.alert({content:"表单中有错误，请检查！"})
	               return;
	         }else{
        	 			this.setState({count1:0});
		        }
				if(parseInt(window.info.deadline_time) < Date.parse(values.endTime)/1000){
					//截至时间不能晚于订购时间，请重新设置
					this.setState({"orderDialog":true});
					return;
				}
	         if(parseInt(window.info.timestemp)+1800 < Date.parse(new Date())/1000){
	    			// 操作授权超过半小时，请重新授权
	    			this.setState({"refreshDialog":true});
	    			return;
	    		}
	         if(!values.is_discount && !values.is_decrease_money && values.is_free_post=="false" && values.is_send_gift=="false"){
	        	 	Dialog.alert({content:"打折或减钱、包邮、送礼品至少有一个，请检查！"});
	        	 	return;
	           }
	         this.props.dispatch(actions.createMjs(values));
	        });
	 }
 }
	onCloseSystemDialog(){
		this.setState({"refreshDialog":false,"orderDialog":false});
		this.props.dispatch(actions.closeDialog());
	}
  render() {
	   const init = this.field.init;
		const formItemLayout = {
				labelCol: {span: 6},
				wrapperCol: {span: 10},
			};
		const tags = <ZhekouTags
							setTag={this.setTag.bind(this)}	
							curTag={this.props.mjs1.name}
							search={this.state.search}
							searchResult={this.searchResult.bind(this)}
							/>
		const lable1 = <div>时间和条件<Badge count={this.state.count1} /></div>
		return (
      <div className="page2-page">
      	<MainNotice />
      	<SystemDialog 
	 		 	 loginError={this.props.mjs1.loginError}
			    creating={this.props.mjs1.creating}
			    message={this.props.mjs1.message}
			    error={this.props.mjs1.error}
				 refreshDialog={this.state.refreshDialog}
				 orderDialog={this.state.orderDialog}
				 onCloseDialog={this.onCloseSystemDialog.bind(this)}
	 			/>

     	 <Form direction="ver"  size="large" field={this.field}>
		        <Tab activeKey={this.state.curStep}>
			        	<Tab.TabPane key={1} onClick={this.handleToStep.bind(this)} tab={lable1}>
				        	<Form.Item label="折扣标签"  required {...formItemLayout}>
									<Search placeholder="选择标签"
										 type="normal"
										 {...init('name', {rules: [{validator:this.checkTag.bind(this)}]})}
										 combox={tags}
										 overlayVisible={this.state.overlayVisible}
										 onInputFocus={this.onVisibleChange.bind(this,true)}
										 hasIcon={false}
										 searchText="　"
										 autoWidth
										 className="tagSearch"
										 onSearch={()=>{}}
										 />
							</Form.Item>
			      	 	<FormMjs1Step1
					   		field={this.field}
					 			formItemLayout={formItemLayout}
								tagName={false}
								setName={()=>{}}
			      	 		
					   			/>
						  <Form.Item
								label="活动范围"
								required 
								{...formItemLayout}>
								<Radio.Group {...init('participate_range', {initValue: '1',rules: [{required: true}]})} >
									<Radio id="some_items" value="1">部分商品</Radio>
									<Radio id="all_shop" value="0">全部商品</Radio>
								</Radio.Group>
						  </Form.Item> 
						  <Form.Item label=" " {...formItemLayout}>
			      	 		<Button onClick={this.handleToStep.bind(this,2)}>下一步</Button>
			      	 	</Form.Item>
			      	</Tab.TabPane>
			        	<Tab.TabPane key={2}  onClick={this.handleToStep.bind(this)} tab="折扣和包邮">
				      	<FormMjs1Step2
						  		field={this.field}
						  		formItemLayout={formItemLayout}
						  		setExcludeArea={()=>{}}
						  		/>
			      	 	<Form.Item label=" " {...formItemLayout}>
			      	 		<Button onClick={this.handleToStep.bind(this,1)}>上一步</Button>
			      	 		&nbsp;
			      	 		<Button onClick={this.handleToStep.bind(this,3)}>下一步</Button>
			      	 	</Form.Item>
			        	</Tab.TabPane>
			        	<Tab.TabPane key={3}  onClick={this.handleToStep.bind(this)} tab="礼物和VIP">
			      	 	<FormMjs1Step3
				      	 	formItemLayout={formItemLayout}
						  		field={this.field}
						  		setGift={()=>{}}
						  		setShopMemberLevel={()=>{}}
			      	 			/>
			      	 	<Form.Item label=" " {...formItemLayout}>
			      	 		<Button onClick={this.handleToStep.bind(this,2)}>上一步</Button>
			      	 		&nbsp;
			      	 		<Button onClick={this.handleToStep.bind(this,4)}>下一步</Button>
			      	 	</Form.Item>
			        	</Tab.TabPane>
		        </Tab>
     	 </Form>
      </div>
    );
  }
}


// map state to props
export default connect((state)=> {
  return {
    mjs1: state.mjs1
  };
})(Mjs1);
